import json
import logging
from datetime import datetime

import requests
from flask import Blueprint

from app import executor
from app.Controllers.BaseController import BaseController
from app.Models.DoorVehicles import DoorVehicles
from app.Models.VehicleParts import VehicleParts
from app.Util import LotClient
from app.Util.LotClient import get_material_details_from_sap

lot = Blueprint('lot', __name__)

log = logging.getLogger('error_msg')


@lot.route('/get10VehicleList', methods=['POST'])
def get_10_vehicle_list():
    print('开始拉去')
    vehicle_list = LotClient.get_10_vehicle_list()
    vehicles = DoorVehicles()
    new_vehicle_list = []
    for vehicle in vehicle_list:
        if not vehicles.get_one_by_vin(vehicle.vin):
            new_vehicle_list.append(vehicle)
    if len(new_vehicle_list) > 0:
        vehicle_parts = VehicleParts()
        for vehicle in new_vehicle_list:
            vehicle_part = vehicle_parts.get_last_by_vehicle_part(vehicle.vehicle_part)
            now = datetime.now()

            if vehicle_part:
                time_diff = now - vehicle_part.created_at
                if int(time_diff.total_seconds() * 1000 + time_diff.microseconds / 1000) < (30 * 60 * 1000):
                    vehicle.door_key = vehicle_part.door_key
                    vehicle.vehicle_part_id = vehicle_part.id
                    vehicles.add(vehicle)
                    continue
            executor.submit(get_sap_part, vehicle)

            # materials = SapMaterialDetailsInfos()
            # material_list = get_material_details_from_sap(vehicle.vehicle_part)
            # if material_list:
            #     material_list.sort(key=lambda m: m.idnrk)
            #     door_key = ''
            #     for material in material_list:
            #         door_key = door_key + material.idnrk
            #     vehicle_part = VehicleParts()
            #     vehicle_part.vehicle_part = vehicle.vehicle_part
            #     vehicle_part.door_key = door_key
            #     vehicle.door_key = door_key
            #     vehicle_part_id = vehicle_part.add(vehicle_part)
            #     vehicle.vehicle_part_id = vehicle_part_id
            #     for material in material_list:
            #         material.vehicle_part_id = vehicle_part_id
            #         materials.add(material)
            # vehicles.add(vehicle)
    return BaseController().success(msg='成功')


def get_sap_part(vehicle):
    material_list = get_material_details_from_sap(vehicle.vehicle_part)
    if material_list:
        material_list.sort(key=lambda m: m.idnrk)
        door_key = ''
        for material in material_list:
            door_key = door_key + material.idnrk
        vehicle_part = VehicleParts()
        vehicle_part.vehicle_part = vehicle.vehicle_part
        vehicle_part.door_key = door_key
        vehicle.door_key = door_key
        vehicle_part_id = add_vehicle_part(vehicle_part)
        vehicle.vehicle_part_id = vehicle_part_id
        for material in material_list:
            material.vehicle_part_id = vehicle_part_id
        add_material_part(material_list)
    add_vehicle(vehicle)


def add_vehicle(vehicle):
    try:
        url = 'http://127.0.0.1:5200/vehicle/addVehicle'
        response = requests.post(url, json=vehicle.to_dict())
        res_data = response.json()
        if res_data['code'] == 200:
            return True
        return False
    except Exception as e:
        log.error(f"拉去总装 10点上线序列失败, 异常：" + str(e))
        return False


def add_vehicle_part(vehicle_part):
    try:
        url = 'http://127.0.0.1:5200/vehicle/addVehiclePart'
        response = requests.post(url, json=vehicle_part.to_dict())
        res_data = response.json()
        if res_data['code'] == 200:
            return res_data['data']
        return None
    except Exception as e:
        log.error(f"拉去总装 10点上线序列失败, 异常：" + str(e))
        return None


def add_material_part(material_list):
    try:
        url = 'http://127.0.0.1:5200/vehicle/addMaterialPart'
        response = requests.post(url, json=json.dumps([m.to_dict() for m in material_list]))
        res_data = response.json()
        if res_data['code'] == 200:
            return True
        return False
    except Exception as e:
        log.error(f"拉去总装 10点上线序列失败, 异常：" + str(e))
        return False
